package net.qhzw.geologr5.gis.service.system.service.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.geologr5.gis.api.system.entity.User;
import net.qhzw.geologr5.gis.common.framework.common.BaseQuery;
import net.qhzw.geologr5.gis.common.framework.utils.JsonResult;
import net.qhzw.geologr5.gis.common.framework.utils.StringUtils;
import net.qhzw.geologr5.gis.common.security.utils.SecurityUtils;
import net.qhzw.geologr5.gis.service.system.dto.BorrowDto;
import net.qhzw.geologr5.gis.service.system.entity.*;
import net.qhzw.geologr5.gis.service.system.mapper.*;
import net.qhzw.geologr5.gis.service.system.pojo.LayerVo2;
import net.qhzw.geologr5.gis.service.system.pojo.ProjectLayerVo;
import net.qhzw.geologr5.gis.service.system.query.GisQuery;
import net.qhzw.geologr5.gis.service.system.query.LayerQuery;
import net.qhzw.geologr5.gis.service.system.service.GisService;
import net.qhzw.geologr5.gis.service.system.utils.UUIDUtil;
import net.qhzw.geologr5.gis.service.system.vo.city.RegionCity;
import net.qhzw.geologr5.gis.service.system.vo.city.RegionProvince;
import net.qhzw.geologr5.gis.service.system.vo.gis.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;


@Service
@Slf4j
public class GisServiceImpl implements GisService {


    @Autowired
    private ProjectTypeMapper projectTypeMapper;

    @Autowired
    private CityMapper cityMapper;

    @Autowired
    private ProjectDataMapper projectDataMapper;

    @Autowired
    private ProjectMapMapper projectMapMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private BorrowDetailsMapper borrowDetailsMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DictMapper dictMapper;

    @Value("${file.projectDate.accsPathPrfx}")
    private String accsPathPrfx;


    /****
     * gsi 首页空间查询
     * @param query
     * @return
     */
   /* @Override
    public JsonResult index(GisQuery query) {
        Map<String, Object> result = new HashMap<>();
        PageHelper.startPage(query.getPage(), query.getLimit());
        try {
            if (query.getCountyId() != null && query.getCountyId() > 0) {
                List<Integer> param = new ArrayList<>();
                param.add(query.getCountyId());
                query.setCityIds(param);
            } else if (query.getCityVoId() != null && query.getCityVoId() > 0) {
                List<RegionCity> cityList = cityMapper.selectRegionCity(query.getCityVoId());
                List<Integer> param = new ArrayList<>();
                param.add(query.getCityVoId());
                for (RegionCity regionCity : cityList) {
                    param.add(regionCity.getCountyId());
                }
                query.setCityIds(param);
            } else if (query.getProvinceId() != null && query.getProvinceId() > 0) {
                //添加省下面的市区县 ...
                List<RegionProvince> provinceList = cityMapper.selectRegionProvince(query.getProvinceId());
                List<Integer> cityIds = new ArrayList<>();
                List<Integer> countyIds = new ArrayList<>();
                for (RegionProvince regionProvince : provinceList) {
                    cityIds.add(regionProvince.getCityId());
                    countyIds.add(regionProvince.getCountyId());
                }
                List<Integer> param = new ArrayList<>();
                param.add(query.getProvinceId());
                for (Integer cityId : cityIds) {
                    param.add(cityId);
                }
                for (Integer countyId : countyIds) {
                    param.add(countyId);
                }
                query.setCityIds(param);
            }
            if (query.getCreateTime() != null && query.getCreateTime().length > 0) {
                query.setStartTime(query.getCreateTime()[0]);
                query.setEndTime(query.getCreateTime()[1]);
            }
            List<GisVo> gisVoList = projectMapMapper.findProjectMap(query);
            PageInfo<GisVo> pageInfo = new PageInfo<>(gisVoList);
            result.put("list", pageInfo.getList());
            result.put("total", pageInfo.getTotal());
            return JsonResult.success(pageInfo);
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }
    }*/
    @Override
    public JsonResult index(GisQuery query) {
        Map<String, Object> result = new HashMap<>();
        PageHelper.startPage(query.getPage(), query.getLimit());
        //查询当前登录的用户信息
        Integer userId = SecurityUtils.getUserId();
        User user = userMapper.selectById(userId);
        if (user == null) {
            return JsonResult.error("服务器获取不到当前登录的用户信息，请退出重新登录");
        }
        //身份权限
        if (user.getIdentity() != null && user.getIdentity() > 0) {
            query.setIdentity(user.getIdentity());
        }
        //文件权限
        if (user.getDictId() != null && user.getDictId() > 0) {
            query.setDictId(user.getDictId());
        }
        //添加项目类型查询条件
        if (query.getProjectTypeId() != null && !StringUtils.isEmpty(query.getProjectTypeId())) {
            String[] split = query.getProjectTypeId().split(",");
            List<Integer> list = new ArrayList<>(split.length);
            for (String s : split) {
                list.add(Integer.valueOf(s));
            }
            query.setTypeId(list);
        }
        //添加时间
        if (query.getCreateTime() != null && query.getCreateTime().length > 0) {
            query.setStartTime(query.getCreateTime()[0]);
            query.setEndTime(query.getCreateTime()[1]);
        }
        //查询条件添加字典值
        if (query.getMineral() != null && !StringUtils.isEmpty(query.getMineral())) {
            query.setMineral(dictMapper.selectNameById(Integer.valueOf(query.getMineral())));
        }

        //查询条件添加城市
        if (query.getCountyId() != null && query.getCountyId() > 0) {
            List<Integer> param = new ArrayList<>();
            param.add(query.getCountyId());
            query.setCityIds(param);
        } else if (query.getCityVoId() != null && query.getCityVoId() > 0) {
            List<RegionCity> cityList = cityMapper.selectRegionCity(query.getCityVoId());
            List<Integer> param = new ArrayList<>();
            param.add(query.getCityVoId());
            for (RegionCity regionCity : cityList) {
                param.add(regionCity.getCountyId());
            }
            query.setCityIds(param);
        } else if (query.getProvinceId() != null && query.getProvinceId() > 0) {
            //添加省下面的市区县 ...
            List<RegionProvince> provinceList = cityMapper.selectRegionProvince(query.getProvinceId());
            List<Integer> cityIds = new ArrayList<>();
            List<Integer> countyIds = new ArrayList<>();
            for (RegionProvince regionProvince : provinceList) {
                cityIds.add(regionProvince.getCityId());
                countyIds.add(regionProvince.getCountyId());
            }
            List<Integer> param = new ArrayList<>();
            param.add(query.getProvinceId());
            for (Integer cityId : cityIds) {
                param.add(cityId);
            }
            for (Integer countyId : countyIds) {
                param.add(countyId);
            }
            query.setCityIds(param);
        }

        List<ProjectMap2> projectMapList = projectMapMapper.selectMapList(query);
        for (ProjectMap2 projectMap2 : projectMapList) {
            List<ProjectData> projectDataList = projectDataMapper.selectByPrijectId(projectMap2.getProjectId());
            projectMap2.setProjectDataList(projectDataList);
            Integer projectDataTotal = projectDataMapper.selectByTotal(projectMap2.getProjectId());
            projectMap2.setProjectDataTotal(projectDataTotal);
        }
        List<GisProjectMap2Vo> projectMap2VoList = new ArrayList<>();
        if (projectMapList != null && !projectMapList.isEmpty()) {
            for (ProjectMap2 projectMap2 : projectMapList) {
                if (projectMap2.getProjectDataList() != null && !projectMap2.getProjectDataList().isEmpty()) {
                    for (ProjectData projectData : projectMap2.getProjectDataList()) {
                        if (projectData.getFileUrl() != null && !StringUtils.isEmpty(projectData.getFileUrl())) {
                            projectData.setFileUrl(accsPathPrfx + projectData.getFileUrl());
                        }
                    }
                }
            }
        }
        for (ProjectMap2 projectMap2 : projectMapList) {
            GisProjectMap2Vo projectMap2Vo = new GisProjectMap2Vo();
            BeanUtils.copyProperties(projectMap2, projectMap2Vo);
            GisProjectVo projectVo = projectMapper.selectGisById(projectMap2.getProjectId());
            projectMap2Vo.setProjectVo(projectVo);
            projectMap2Vo.setMapId(projectMap2.getId());
            projectMap2VoList.add(projectMap2Vo);
        }

        PageInfo<ProjectMap2> pageInfo = new PageInfo<>(projectMapList);
        return JsonResult.success(pageInfo);
    }

    /***
     * 图层查询
     * @return
     */
    @Override
    public JsonResult getLayer(LayerQuery query) {
        try {
            PageHelper.startPage(query.getPage(), query.getLimit());
            //查询条件添加城市
            if (query.getCountyId() != null && query.getCountyId() > 0) {
                List<Integer> param = new ArrayList<>();
                param.add(query.getCountyId());
                query.setCityIds(param);
            } else if (query.getCityVoId() != null && query.getCityVoId() > 0) {
                List<RegionCity> cityList = cityMapper.selectRegionCity(query.getCityVoId());
                List<Integer> param = new ArrayList<>();
                param.add(query.getCityVoId());
                for (RegionCity regionCity : cityList) {
                    param.add(regionCity.getCountyId());
                }
                query.setCityIds(param);
            } else if (query.getProvinceId() != null && query.getProvinceId() > 0) {
                //添加省下面的市区县 ...
                List<RegionProvince> provinceList = cityMapper.selectRegionProvince(query.getProvinceId());
                List<Integer> cityIds = new ArrayList<>();
                List<Integer> countyIds = new ArrayList<>();
                for (RegionProvince regionProvince : provinceList) {
                    cityIds.add(regionProvince.getCityId());
                    countyIds.add(regionProvince.getCountyId());
                }
                List<Integer> param = new ArrayList<>();
                param.add(query.getProvinceId());
                for (Integer cityId : cityIds) {
                    param.add(cityId);
                }
                for (Integer countyId : countyIds) {
                    param.add(countyId);
                }
                query.setCityIds(param);
            }

            //添加时间
            if (query.getCreateTime() != null && query.getCreateTime().length > 0) {
                query.setStartTime(query.getCreateTime()[0]);
                query.setEndTime(query.getCreateTime()[1]);
            }

            //添加项目类型查询条件
            if (query.getProjectTypeId() != null && !StringUtils.isEmpty(query.getProjectTypeId())) {
                String[] split = query.getProjectTypeId().split(",");
                List<Integer> list = new ArrayList<>(split.length);
                for (String s : split) {
                    list.add(Integer.valueOf(s));
                }
                query.setTypeId(list);
            }


            //项目类型数据
            List<LayerVo2> layerVoList = projectTypeMapper.selectLayer(query);
            PageInfo<LayerVo2> pageInfo = new PageInfo<>(layerVoList);
            return JsonResult.success(pageInfo);
        } catch (Exception e) {
            log.error("查询图层查询失败==GisServiceImpl==method:getLayer==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }


    /***
     * 申请资源
     * @param applyRes
     * @return
     */
    @Override
    public JsonResult reqResources(ApplyResource applyRes) {
        List<Integer> projectDataIds = applyRes.getProjectDataIds();
        List<ProjectData> projectDataList = projectDataMapper.selectByIdList(projectDataIds);
        List<Integer> projectMapIds = applyRes.getProjectMapIds();
        List<ProjectMap> projectMapList = projectMapMapper.selectByIdList(projectMapIds);
        //获取当前登录的用户id
        Integer userId = SecurityUtils.getLoginUser().getUserId();
        //日期格式流水号
        BorrowDto borrowDto = new BorrowDto();
        String uUid = UUIDUtil.getUUid();
        borrowDto.setId(uUid);
        borrowDto.setBorroTime(new Date());
        borrowDto.setDownloadCount(0);
        borrowDto.setUserId(userId);
        borrowDto.setOperation(0);
        borrowDto.setAudit(0);
        borrowDto.setBorroNo(getSerlNum());
        borrowMapper.insert(borrowDto);
        List<BorrowDetails> borrowDetailsList = new ArrayList<>();

        for (ProjectData projectData : projectDataList) {
            BorrowDetails borrowDetails = new BorrowDetails();
            borrowDetails.setFileId(projectData.getId());
            borrowDetails.setBorrowId(uUid);
            borrowDetails.setProjectId(projectData.getProjectId());
            borrowDetailsList.add(borrowDetails);

        }
        for (ProjectMap projectMap : projectMapList) {
            BorrowDetails borrowDetails = new BorrowDetails();
            borrowDetails.setMapId(projectMap.getId());
            borrowDetails.setBorrowId(uUid);
            borrowDetails.setProjectId(projectMap.getProjectId());
            borrowDetailsList.add(borrowDetails);
        }

        for (BorrowDetails borrowDetails : borrowDetailsList) {
            borrowDetailsMapper.insert(borrowDetails);
        }

        return JsonResult.success();
    }


    /***
     * 图层查询
     * @return
     */
//    @Override
//    public JsonResult getLayer(LayerQuery query) {
//        try {
//            //项目类型数据
//            List<ProjectType> projectTypeList = projectTypeMapper.selectprojectType(null);
//            //根节点
//            List<ProjectType> rootNode = new ArrayList<>();
//            for (ProjectType projectType : projectTypeList) {
//                if (projectType.getPid() == 0) {
//                    rootNode.add(projectType);
//                }
//            }
//            //获取根节点下的所有子节点
//            for (ProjectType projectType : rootNode) {
//                List<ProjectType> child = getChild(projectType.getId(), projectTypeList);
//                projectType.setProjectTypeList(child);
//            }
//            log.info("rootNode: ==  {}", JSON.toJSONString(rootNode));
//
//            PageInfo<LayerVo2> pageInfo = new PageInfo<>();
//            for (ProjectType projectType : rootNode) {
//            }
//            return JsonResult.success(rootNode);
//        } catch (Exception e) {
//            log.error("查询全部项目类别失败==ProjectTypeServiceImpl==method:findAll==errMsg: {}", e.getMessage());
//            return JsonResult.error(e.getMessage());
//        }
//    }


    /***
     *
     * @return
     */

    /****
     * 返回流水号 serlNum
     *          2021081200200
     * @return
     */
    private String getSerlNum() {
        String serlNumMax = borrowMapper.selectSerlNumMax();
        String uid_pfix = getTimeStr();
        String max_code = serlNumMax;
        String comment_code = "";
        if (max_code != null && max_code.contains(uid_pfix)) {
            String uid_end = max_code.substring(8, max_code.length());
            //吧String类型00011 转化为int的1
            int endNum = Integer.parseInt(uid_end);
            //结果为100002
            int tmpNum = 100000 + endNum + 1;
            //把100002首为1去掉
            comment_code = uid_pfix + subStr("" + tmpNum, 1);
        } else {
            comment_code = uid_pfix + "00001";
        }
        return comment_code;
    }

    /***
     * 把100002的首尾1去掉的方法
     * @param str
     * @param start
     * @return
     */
    private String subStr(String str, int start) {
        if (str == null || str.equals("")) {
            return "";
        }
        if (start < str.length()) {
            return str.substring(start);
        } else {
            return "";
        }
    }

    private String getTimeStr() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
    }

    /***
     * 获取所有的子节点
     * @param id 父id
     * @param projectTypes 匹配数据
     * @return
     */
    private List<ProjectType> getChild(Integer id, List<ProjectType> projectTypes) {
        //子节点
        List<ProjectType> childList = new ArrayList<>();
        for (ProjectType projectType : projectTypes) {
            if (id.equals(projectType.getPid())) {
                childList.add(projectType);
            }
        }
        for (ProjectType projectType : childList) {
            List<ProjectType> child = getChild(projectType.getId(), projectTypes);
            projectType.setProjectTypeList(child);
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if (childList.size() == 0) {
            return new ArrayList<ProjectType>();
        }
        return childList;
    }
}
